<?php

namespace app\api\controller\v1\store\login;

use app\admin\model\DataUser;
use app\admin\model\PaymentConfig;
use app\api\controller\Api;
use app\api\services\v1\store\StoreService;
use think\exception\HttpResponseException;
use WeMini\Crypt;

/**
 * 微信小程序入口
 * @class Wxapp
 * @package plugin\account\controller\api
 */
class WxLogin extends Api
{

    private  $services;


    private  $params;

    /**
     * 小程序配置参数
     * @var array
     */

    /**
     * 接口初始化
     */
    protected function initialize()
    {
        parent::initialize();
        $pay  = new PaymentConfig();
        $pay = $pay->column('content')[0];
        $config = json_decode($pay,true);
        $this->params = [
            'appid'      => $config['appid'] ?? '',
            'appsecret'  => $config['appkey'] ?? '',
        ];
        $this->services = app()->make(StoreService::class);


    }





    /**
     * 绑定openid
     */
    public function bind()
    {
        try {
            $rule = [
                'code'    => 'require',
            ];
            $message  =   [
                'code.require' => '凭证编码为空',
            ];
            $this->validate($this->post, $rule,$message);
            [$openid, $unionid, $sesskey] = $this->applySesskey($this->post['code']);
            $user = new DataUser();
            $user->where(['id'=>$this->user['id'],'usertype'=>1])->findOrEmpty();
            if($user->isEmpty())$this->error('用户不存在');
            $user->openid = $openid;
            $user->unionid = $unionid;
            $user->save();
            $this->success('绑定成功！', $user);
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $this->error("处理失败，{$exception->getMessage()}");
        }
    }

    /**
     * 换取会话
     */
    public function session()
    {
        try {
            $rule = [
                'code'    => 'require',
            ];
            $message  =   [
                'code.require' => '凭证编码为空',
            ];
            $this->validate($this->post, $rule,$message);
            [$openid, $unionid, $sesskey] = $this->applySesskey($this->post['code']);
            $data = [
                'appid' => $this->params['appid'],
                'openid' => $openid,
                'unionid' => $unionid,
                'session_key' => $sesskey,
            ];
            $this->success('授权换取成功！', $data);
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $this->error("处理失败，{$exception->getMessage()}");
        }
    }



    /**
     * 快速获取手机号
     * @return void
     */
    public function phone()
    {
        try {
            $rule = [
                'openid'    => 'require',
                'code'    => 'require',
            ];
            $message  =   [
                'code.require' => '凭证编码为空',
                'openid.require' => '用户编号为空',
            ];
            $this->validate($this->post, $rule,$message);
            $result = Crypt::instance($this->params)->getPhoneNumber($this->post['code']);
            if (is_array($result)) {
                if(!empty($result['phone_info']['phoneNumber'])){
                    $data = ['openid' => $this->request->param('openid'),'phone'=> $result['phone_info']['phoneNumber']];
                    $data['usertype'] = 1;
                    $user = new DataUser();
                    $user = $user->where(['phone'=>$result['phone_info']['phoneNumber'],'usertype'=>$data['usertype']])->findOrEmpty();
                    if($user->isEmpty()){
                        $user->openid = $this->request->param('openid');
                        $user->phone = $result['phone_info']['phoneNumber'];
                        $user->usertype = $data['usertype'];
                        $user->save();
                    }
                    $service = $this->services->login($data,$this->request->ip());
                    if(!empty($service)){
                        $this->success('登陆成功',$service);
                    }else{
                        $this->error('登陆失败,手机号错误');
                    }
                }else{
                    $this->success('登陆失败！', $result);
                }
            } else {
                $this->error('数据解析失败！');
            }
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {

            $this->error("数据处理失败，{$exception->getMessage()}");
        }
    }


    /**
     * 换取会话授权
     * @param string $code 授权编号
     * @return array [openid, unionid, sessionkey]
     */
    private function applySesskey(string $code): array
    {
        try {
            $cache = $this->app->cache->get($code, []);
            if (isset($cache['openid']) && isset($cache['session_key'])) {
                return [$cache['openid'], $cache['unionid'] ?? '', $cache['session_key']];
            }
            $result = Crypt::instance($this->params)->session($code);
            if (isset($result['openid']) && isset($result['session_key'])) {
                $this->app->cache->set($code, $result, 7200);
                return [$result['openid'], $result['unionid'] ?? '', $result['session_key']];
            } else {
                $this->error($result['errmsg'] ?? '授权换取失败！');
            }
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $this->error("换取授权失败，{$exception->getMessage()}");
        }
    }


}